#include "music.h"
#include <QPushButton>
#include <QDir>
#include <QSlider>
#include <QGridLayout>
#include <QDebug>
#include <QHBoxLayout>
#include <QTime>
#include <QTimer>
#include <qfile.h>
#include <QFile>
#include <QtGui>
#include <QPixmap>
#include"configargs.h"



int size_H =550;
int size_W =480;

int fd;
int tm =0;            //分钟
int ts =0;            //秒
int startflag=0;
int stopflag=0;
int usr_volume=0;

Music::Music(QWidget *parent): JDialog(parent)
{
    gifcurren=0;
    choncehanv=0;
    musiccount=0;
    volume = 0;
    timer = NULL;
    soundLrc = new QLabel;
    listWidget = new QListWidget;
   // soundLrc->setText("暂时无歌词功能");
  //  soundLrc->setFixedSize(size_H+160,size_W);
   // soundLrc->setStyleSheet("background-color:rgb(15,36,89)");

    if(g_lcdsize == LCDSIZE_1024x768 || g_lcdsize == LCDSIZE_1280x800){
		size_H = 400;
		size_W = 370;
		soundLrc->setFixedSize(size_H+40,size_W);
		listWidget->setFixedSize(size_H+10,size_W);
		listWidget->setIconSize(QSize(50,50));
    }else if(g_lcdsize == LCDSIZE_800x600){
        size_H = 300;
        size_W = 260;
        soundLrc->setFixedSize(size_H+40,size_W);
        listWidget->setFixedSize(size_H+10,size_W);
        listWidget->setIconSize(QSize(50,50));
    }else if(g_lcdsize == LCDSIZE_800x480){
        size_H = 300;
        size_W = 260;
        soundLrc->setFixedSize(size_H+40,size_W);
        listWidget->setFixedSize(size_H+10,size_W);
        listWidget->setIconSize(QSize(50,50));
    }else if(g_lcdsize == LCDSIZE_480x272){
        size_H = 250;
        size_W = 130;
        soundLrc->setFixedSize(size_H+40,size_W);
        listWidget->setFixedSize(size_H+10,size_W);
        listWidget->setIconSize(QSize(25,25));
    }

    currentsound =0;
    Timer_flag=0;
    nCount=0;
    down = new QPushButton;
    up = new QPushButton;
    setting = new QPushButton;
    starMusic = new QPushButton;
    musicclosebut = new QPushButton;
    musicstopbut = new QPushButton;
	volumeup = new QPushButton;
	volumedown = new QPushButton;

    connect(listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(chosemusic()));
    listWidget->clear();
    listWidget->setWordWrap(true);
    listWidget->setAutoScroll(true);
    listWidget->setResizeMode(QListView::Adjust);
    listWidget->setMovement(QListView::Static);

    //listWidget->setStyleSheet("background-color:rgb(80,100,89);pading: 20px;border: 5px solid rgba(80,100,89,0.5)");
    listWidget->setStyleSheet("QListWidget{border:1px solid gray; color:black; }"
                           "QListWidget::Item{padding-top:20px; padding-bottom:4px; }"
                           "QListWidget::Item:hover{background:skyblue; }"
                           "QListWidget::item:selected{background:lightgray; color:red; }"
                           "QListWidget::item:selected:!active{border-width:0px; background:lightgreen; }"
                           );


   // soundLrc->setContentsMargins(0,0,0,0);
  //  movie = new QMovie(":/images/cdbofang4.gif");
 //   movie->setScaledSize(QSize(size_H+140,size_W));
 //   soundLrc->setMovie(movie);
  //  movie->start();
   // musicpix = new QPixmap;
  //  musicpix->load(":/images/bofang1.png");
	QPixmap pixmap1;

  	if(g_lcdsize == LCDSIZE_480x272)
  	{
		pixmap1.load(":/images/bofang2.png");
  	}else{
  		pixmap1.load(":/images/bofang1.png");
    }

    soundLrc->setPixmap(pixmap1);


    starttime = new QTimeEdit;
    starttime->setDisplayFormat("hh:mm:ss");
    starttime->setDisabled(true);
    overtime = new QTimeEdit;
    overtime->setDisplayFormat("hh:mm:ss");
    overtime->setDisabled(true);

    volum = new QLabel;
    volum->setText(tr("音量:"));

    havedrun =new QLabel;
    havedrun->setText("播放进度:");

    down->setText(tr("下一首"));
    up->setText(tr("上一首"));
    setting->setText(tr("打开目录"));
    starMusic->setText(tr("播放"));
    musicclosebut->setText("关闭");
    musicstopbut->setText("停止");
	volumeup->setText("音量+");
	volumedown->setText("音量-");
	
   // musicstopbut->setText("歌词");
    musicstopbut->setShortcut(QKeySequence(QLatin1String("+")));

    slider = new QSlider(Qt::Horizontal);                //音量
    runSlider = new QSlider(Qt::Horizontal);
	
    slider->setMinimum(0);
    slider->setMaximum(20);  //根据madplay -a属性.声音范围 -175 ~ +18,播放时默认10dB;
    slider->setValue(8);
    slider->setTickPosition(QSlider::TicksBelow);
	
    if(1){
    slider->setStyleSheet("  \
          QSlider::add-page:Horizontal\
          {     \
             background-color: rgb(87, 97, 106);\
             height:4px;\
          }\
          QSlider::sub-page:Horizontal \
         {\
             background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(200,100,180, 200), stop:1 rgba(17,180,230, 230));\
             height:4px;\
          }\
         QSlider::groove:Horizontal \
         {\
             background:transparent;\
             height:6px;\
         }\
         QSlider::handle:Horizontal \
         {\
             height: 30px;\
             width:8px;\
             border-image: url(:/images/ic_music_thumb.png);\
             margin: -8 0px; \
         }\
         ");
          runSlider->setStyleSheet("  \
                QSlider::add-page:Horizontal\
                {     \
                   background-color: rgb(87, 97, 106);\
                   height:4px;\
                }\
                QSlider::sub-page:Horizontal \
               {\
                   background-color:qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(231,80,229, 255), stop:1 rgba(7,208,255, 255));\
                   height:4px;\
                }\
               QSlider::groove:Horizontal \
               {\
                   background:transparent;\
                   height:6px;\
               }\
               QSlider::handle:Horizontal \
               {\
                   height: 30px;\
                   width:8px;\
                   border-image: url(:/images/ic_music_thumb.png);\
                   margin: -8 0px; \
               }\
               ");

      }

    runSlider->setMinimum(0);
    runSlider->setMaximum(256);
    runSlider->setValue(0);
    runSlider->setTickPosition(QSlider::TicksBelow);
    runSlider->setEnabled(false);
    giftimer =new QTimer(this);
    timerx = new QTimer(this);
 //   timer->start(200);        //设置定是器的时间为一秒

    connect(starMusic, 		SIGNAL(clicked()), 			this,   SLOT(startorstop()));
    connect(up,         	SIGNAL(clicked()),  		this,   SLOT(slotUp()));
    connect(down,       	SIGNAL(clicked()), 			this, 	SLOT(slotDown()));
//    connect(slider,			SIGNAL(valueChanged(int)),			SLOT(slotGetVol()));
    connect(setting,		SIGNAL(clicked()),			this,	SLOT(musicsetting()));
    connect(musicstopbut,	SIGNAL(clicked()),			this,	SLOT(musicstop()));
    connect(musicclosebut,	SIGNAL(clicked()),			this,	SLOT(musicclose()));
    connect(timerx,			SIGNAL(timeout()),			this,	SLOT(slotShowTime()));
    connect(giftimer,		SIGNAL(timeout()),			this,	SLOT(slotShowgifTime()));
	connect(volumeup,		SIGNAL(clicked()),			this,	SLOT(volumup1dB()));
	connect(volumedown,		SIGNAL(clicked()),			this,	SLOT(volumdown1dB()));

//    fd =::open("/dev/snd/controlC1", O_WRONLY);        //打开mixer设备，用于音量调节
/*
    fd =::open("/dev/snd/pcmC0D0p", O_WRONLY);        //打开mixer设备，用于音量调节
    if (fd ==  - 1)
    {
        perror("unable to open /dev/snd/pcmC0D0p");
        exit(1);
    }
*/
   
    usr_volume=250;

 
    command=tr("madplay -m  -Q -a "); //-m双声道 -v获取播放时间 -Q忽略警告 -a 指定音量大小

    system("echo 0 > /tmp/volume"); //保存当前音量 0dB

    backend = tr(" &");                                 //后台播放
    QGridLayout * musicLayout = new QGridLayout;
    QHBoxLayout * subHLayout = new QHBoxLayout;
    QVBoxLayout * subVLayout = new QVBoxLayout;
    QHBoxLayout * subH3Layout = new QHBoxLayout;
	
    subHLayout->addWidget(up);
    subHLayout->addWidget(starMusic);
    subHLayout->addWidget(down);  	
	subH3Layout->addWidget(volum);
	subH3Layout->addWidget(slider);
	subH3Layout->addWidget(volumedown);
	subH3Layout->addWidget(volumeup);
	   
    subVLayout->addLayout(subH3Layout);
    subVLayout->addLayout(subHLayout);

    QHBoxLayout * subHLayout1 = new QHBoxLayout;
    QVBoxLayout * subVLayout1 = new QVBoxLayout;
    QHBoxLayout * subH4Layout = new QHBoxLayout;
    subHLayout1->addWidget(setting);
    subHLayout1->addWidget(musicclosebut);
    subHLayout1->addWidget(musicstopbut);
 //   subH4Layout->addWidget(timertmp);
    subH4Layout->addWidget(starttime);
    subH4Layout->addWidget(runSlider);
    subH4Layout->addWidget(overtime);
    subVLayout1->addLayout(subH4Layout);
    subVLayout1->addLayout(subHLayout1);

  //  subLayout->addLayout(slider,0,1,1,1);
    musicLayout->addWidget(soundLrc,    0,0,1,1);
    musicLayout->addWidget(listWidget,  0,2,1,1);
    musicLayout->addLayout(subVLayout1, 1,0,1,1);
    musicLayout->addLayout(subVLayout,  1,2,1,1);

    musicLayout->setMargin(20);
    musicLayout->setSpacing(10);

    QFrame *pFrame = new QFrame;
    pFrame->setLayout(musicLayout);

    QGridLayout *pMainLayout = new QGridLayout;
    pMainLayout->addWidget(pFrame, 0, 0, 1, 1);
    pMainLayout->setContentsMargins(40, 15, 40, 15);

    pFrame->setObjectName("musicFrame");
    this->setJLayout(pMainLayout);
    this->setJTitle(tr("MP3音乐播放器"));

    system("killall -9 madplay");

    QFile file1("/usrfs/qtapp/music.conf");
    file1.open(QFile::ReadOnly);
    setpath=file1.readAll();
    file1.close();
	
//	setpath.trimmed();
	setpath.replace(QString("\n"), QString(""));

	
    setpath.append("/");
 //    qDebug("/////////////////");
     qDebug() << "in Music:" << setpath;
    if(setpath.isEmpty()){
       //"setpath.isEmpty()");
       musicsettingonce();
       //)<<setpath;
    }else {
     //   setpath
         qDebug("else");
    }

#if 0
    QFile file2("/usrfs/qtapp/musichave.conf");
    file2.open(QFile::ReadOnly);
    QString setpathtmp=file2.readAll();
    file2.close();
    if(setpathtmp.isEmpty()){
    	scanMusicFun0();
  //  qDebug("0");
    }
    else
    scanMusicFun();
  //  giftimer->start(10000);
#endif
}

void Music::slotShowgifTime()
{
 /*  // movie->stop();
    giftimer->stop();
    gifcurren++;
    QPixmap pixmaptmp1(":/images/bofang1.png");
    QPixmap pixmaptmp2(":/images/bofang2.png");
    QPixmap pixmaptmp3(":/images/bofang3.png");
    QPixmap pixmaptmp4(":/images/bofang1.png");
    QPixmap pixmaptmp5(":/images/bofang2.png");
    QPixmap pixmaptmp6(":/images/bofang3.png");
    switch (gifcurren) {
//    case 1: movie->setFileName(":/images/cdbofan4.gif");break;
//    case 2: movie->setFileName(":/images/cdbofang2.gif");break;
//    case 3: movie->setFileName(":/images/cdbofang3.gif");break;
//    case 4: movie->setFileName(":/images/cdbofang1.gif");break;
//    case 5: movie->setFileName(":/images/cdbofang5.gif");break;
//    case 6: movie->setFileName(":/images/cdbofang7.gif");break;
    case 1:   soundLrc->setPixmap(pixmaptmp1);break;
    case 2:   soundLrc->setPixmap(pixmaptmp2);break;
    case 3:   soundLrc->setPixmap(pixmaptmp3);break;
    case 4:   soundLrc->setPixmap(pixmaptmp4);break;
    case 5:   soundLrc->setPixmap(pixmaptmp5);break;
    case 6:   soundLrc->setPixmap(pixmaptmp6);break;
    default:
        break;
    }
    if(gifcurren==7)
        gifcurren=0;
  //  movie->start();
    giftimer->start();
    //*/
}




void Music::information()
{

       // char *filename1 = filePath+fileName;
       position = 0;
       char *filename1;
       QString tmp=filePath+fileName;
       QByteArray ba=tmp.toLocal8Bit();
       filename1=ba.data();
       filename1[tmp.length()] = '\0';

       qDebug("LinDbg: [%s]%d, fineName:%s", __FUNCTION__, __LINE__, filename1);

        fp = fopen(filename1, "rb");
        if(NULL == fp)
        {
            qDebug("LinDbg: [%s]%d, cannot open file", __FUNCTION__, __LINE__);
            return;
        }

        fineframe();            //找帧头
        qDebug("LinDbg: [%s]%d", __FUNCTION__, __LINE__);
        obtaim_info();          //获取比特率和采样频率
        qDebug("LinDbg: [%s]%d", __FUNCTION__, __LINE__);
        readinfo();             //读数据
}
/*找帧头*/
void Music::fineframe()
{

   //"position =%d",position);
    fseek(fp, position, SEEK_SET);                //初始化中position为0
    fread(Mp3_ID3V1.Header, 3, 1, fp);             //从fp中读三个字节到Mp3_ID3V1.Header

    if((Mp3_ID3V1.Header[0]=='I') && (Mp3_ID3V1.Header[1]=='D') && (Mp3_ID3V1.Header[2]==0x33))
    {//判断
        //QMessageBox::information(this,"Hi,man.",tr("it has id3v2 .."));
        //"if");
        obtain_ID3V2size();                     //获取ID3V2的大小，获取值为整型
        
        str = str.number(first);
        position = str.toLong();                //这两步将整型转换成long型
        
        fseek(fp, position, SEEK_SET);            //指针从0跳到position处
        fread(Mp3_ID3V1.Header, 3, 1, fp);         //从fp中读取三个字节存到Mp3_ID3V1.Header
    }
}
/*获取文件ID3V2大小*/
void Music::obtain_ID3V2size()
{
    fseek(fp, 6L, SEEK_SET);              //跳到距离开头6个字节处
    fread(Mp3_ID3V2.Size, 4, 1, fp);       //按规格读取数据

    /*根据算法技术ID3V2的大小，复制到first中*/
    first = (Mp3_ID3V2.Size[0]&0x7F)*0x200000 + (Mp3_ID3V2.Size[1]&0x7F)*0x400 + (Mp3_ID3V2.Size[2]&0x7F)*0x80 + (Mp3_ID3V2.Size[3]&0x7F) + 10;
}
/*根据不同类型文件来获取文件时间*/
void Music::readinfo()
{
        /*跳到XING指定位置读取数据,存到temp中*/
        position = 0 + 4 + 32;
        fseek(fp, position, SEEK_SET);
        fread(temp, 4, 1, fp);

        /*跳到VBP指定位置读取数据,存到temp1中*/
        position = 0+32;
        fseek(fp, position, SEEK_SET);
        fread(temp1, 4, 1, fp);

        if((temp[0]=='X')&(temp[1]=='i')&(temp[2]=='n')&(temp[3]=='g'))	//如果获取的是XING头，则按规格获取xing头文件时间.
        {
			qDebug("is XING\n");
            position = (0+4+32)+8;
            obtain_VBRtime();

        }
        else if((temp1[0]=='V')&(temp1[1]=='B')&(temp1[2]=='R')&(temp1[3]=='I'))	//如果获取的是VBRI头，则按规格获取VBR头文件时间.
        {
			qDebug("is VBRI\n");
            position = (0+32)+14;
            obtain_VBRtime();

        }
        else		//如果都不是，那就按CBP规格来获取CBP时间
        {
        	qDebug("is else\n");
            obtain_CBPtime();
        }

}

/*获取比特率和采样频率*/
void Music::obtaim_info()
{
    char number = Mp3_ID3V1.Header[2] & 0xf0;
    //"number=%d",number);
    switch(number)
    {
    case 0x10:
            bitrate = 32;
            break;
    case 0x20:
            bitrate = 40;
            break;
    case 0x30:
            bitrate = 48;
            break;
    case 0x40:
            bitrate = 56;
            break;
    case 0x50:
            bitrate = 64;
            break;
    case 0x60:
            bitrate = 80;
            break;
    case 0x70:
            bitrate = 96;
            break;
    case 0x80:
            bitrate = 112;
            break;
    case 0x90:
            bitrate = 128;
            break;
    case 0xa0:
            bitrate = 160;
            break;
    case 0xb0:
            bitrate = 192;
            break;
    case 0xc0:
            bitrate = 224;
            break;
    case 0xd0:
            bitrate = 256;
            break;
    case 0xe0:
            bitrate = 320;
            break;
    default:
            bitrate = 128;
    }


    char number1 = Mp3_ID3V1.Header[2] & 0x0c;
    switch(number1)
    {
	    case 0x00:
	        sampling = 44100;
	        break;
	    case 0x04:
	        sampling = 48000;
	        break;
	    case 0x08:
	        sampling = 32000;
	        break;
    }

	qDebug("bitrate: %d sampling:%d\n", bitrate, sampling);
}
/*获取CBP文件的时间*/
void Music::obtain_CBPtime()
{

    qint64 fsize;
    QFileInfo filesize(filePath+fileName);
    fsize = filesize.size();

    int sizetmp = fsize;

    //"fzize= %d , bitrate = %d",sizetmp,bitrate);

    second = fsize * 8 / bitrate / 1000;

    str1 = str1.number(second);
  //  textedit->setText(str1);

    displaytime();                  //显示时间

//    obtain_ID3V1();                 //显示ID3V1信息，可要可不要。
}
/*显示ID3V1信息*/
void Music::obtain_ID3V1()
{

    fseek(fp,-128L,SEEK_END);
    fread(Mp3_ID3V1.Header,3,1,fp);

    fseek(fp,-125L,SEEK_END);
    fread(Mp3_ID3V1.Title,30,1,fp);

    fseek(fp,-95L,SEEK_END);
    fread(Mp3_ID3V1.Artist,30,1,fp);

    fseek(fp,-65L,SEEK_END);
    fread(Mp3_ID3V1.Album,30,1,fp);

    fseek(fp,-35L,SEEK_END);
    fread(Mp3_ID3V1.Year,4,1,fp);

    fseek(fp,-31L,SEEK_END);
    fread(Mp3_ID3V1.Comment,28,1,fp);

    fseek(fp,-1L,SEEK_END);
    fread(Mp3_ID3V1.Cenre,1,1,fp);


  //  textedit->append(fn1.at(i));

    str = QString(Mp3_ID3V1.Header);
 //   textedit->append(str);
    str = QString(Mp3_ID3V1.Title);
    //textedit->append(str);
    str = QString(Mp3_ID3V1.Artist);
  //  textedit->append(str);
   // authorLabel->setText(tr(Mp3_ID3V1.Artist));

    str = QString(Mp3_ID3V1.Album);
    //textedit->append(str);
    str = QString(Mp3_ID3V1.Year);
   // textedit->append(str);
    str = QString(Mp3_ID3V1.Comment);
//    textedit->append(str);
    str = QString(Mp3_ID3V1.Cenre);
  //  textedit->append(str);

}
/*获取VBR文件的时间*/
void Music::obtain_VBRtime()
{
    fseek(fp,position,SEEK_SET);
    fread(date,4,1,fp);

    str = QString(date);
    sumnumber = str.toInt();

    second = sumnumber*(1152*(1/sampling));

    displaytime();
}
/*显示时间*/
void Music::displaytime()
{
    QTime time(0,0,0);
	
    time = time.addSecs(second);
    qDebug("second  = %d",second);
    
    overtime->setTime(time);
}

/*时间、进度条同步模块*/

void Music::someset()
{
    runSlider->setRange(0,second);         //设定水平条范围为0到MP3总时间
    runSlider->setValue(0);                //设置初始值为0
  //  connect(runSlider,SIGNAL(sliderMoved(int)),this,SLOT(slotchangeplay()));
    //当拖动水平条时，进入槽函数，跳转到制定时间进行播放。

  //  inittime.isValid(0,0,0);
  //  starttime->setTime(inittime);

    if(0 == Timer_flag)		//以时间标志位来判断，确保定时器只创建一个，我们也只需要一个。
    {
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(slottime()));//如果定时器溢出，进入slottime槽函数，实现水平进度条和开始时间的同步
    
    Timer_flag = 1;
    }

    timer->start(1000);                 //以一秒为大小，开始运行定时器
}
void Music::slottime()
{

    runSlider->setValue((runSlider->value())+1);
    //水平进度条的值+1
    addtime = inittime.addSecs(runSlider->value());
    //获取水平进度条的值
    starttime->setTime(addtime);
    //水平进度条的值赋给开始时间

    if(second == runSlider->value())
    {//判断如果水平条的值等于MP3总时间说明播放结束,做一下设置.
        timer->stop();                          //停止定时器
        runSlider->setValue(0);        			//水平条置0
        addtime = inittime.addSecs(0);          //获取QTime类对象值为0
        starttime->setTime(addtime);            //开始时间置0
        Music::slotDown();						//下一首
    }
}

void Music::volumup1dB()
{
	QFile vol_file("/tmp/volume");

	if(volume < 18)
		volume += 1.5;

	qDebug("up vol:%f\n", volume);

	vol_file.open(QFile::WriteOnly | QFile::Truncate);
	QTextStream str_temp(&vol_file);
	str_temp << volume;

	vol_file.close();
	
	system("amixer -c 0 set PCM 1dB+");
	slider->setValue((slider->value()) + 1);
}

void Music::volumdown1dB()
{
	QFile vol_file("/tmp/volume");

	if(volume > -12)
		volume -= 1.5;

	qDebug("down vol:%f\n", volume);

	vol_file.open(QFile::WriteOnly | QFile::Truncate);
	QTextStream str_temp(&vol_file);
	str_temp << volume;

	vol_file.close();
	
	system("amixer -c 0 set PCM 1dB-");
	slider->setValue((slider->value()) - 1);
}



void Music::musicstop()
{
    stopflag = 1;
    startflag = 1;
    //qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);
    system("killall -STOP madplay &");
    //qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);

    if(timer != NULL){
        if(timer->isActive())
            timer->stop();
    }//停止定时器

    //qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);
    runSlider->setValue(0);        			//水平条置0
    //qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);
    addtime = inittime.addSecs(0);          //获取QTime类对象值为0
    //qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);
    starttime->setTime(addtime);            //开始时间置0
    //qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);
    starMusic->setText(tr("播放"));

}

void Music::musicclose()
{
  //  movie->stop();
    system("killall -9 madplay &");
    this->close();
}

void Music::keepVolUmeFixed()
{
//	char buf[72];

//	sprintf(buf, "%s %d", "amixer cset numid=7,iface=MIXER,name='PCM Playback Volume' ", slider->value());
//	sprintf(buf, "%s %d%s", "amixer -c 0 set PCM  ", slider->value(), "dB &");



//	qDebug("volume: %d dB buf_up: %s\n", slider->value(), buf);
//	system(buf); // 切换歌曲时保持音量不变

/*
	int tmp;

	tmp = slider->value() - 25;
	qDebug("tmp: %d\n", tmp);

	if(tmp > 0)
	{
		for(int i=0; i<=tmp; i++)
		{
			system("amixer -c 0 set PCM 1dB+");
		}
	}else{
		tmp = -tmp;
		for(int i=0; i<=tmp; i++)
		{
			system("amixer -c 0 set PCM 1dB-");
		}
	}
*/

	slider->setValue(25);

}


void Music::scanMusicFun()
{
    musiccount=0;
	
	QFile file1("/usrfs/qtapp/music.conf");

    file1.open(QFile::ReadOnly);

	setpath.clear();
    setpath=file1.readAll();
	setpath.replace(QString("\n"), QString(""));

	
    file1.close();

    setpath.append("/");

	qDebug()<<"setpath:"<<setpath;

	QDir dir(setpath);
	
    filePath = setpath;                    //设置播放目录
    listWidget->clear();
 
    musicList = dir.entryList(QDir::Files,QDir::Name);   //遍历播放目录下的所有歌曲
 
    nCount = musicList.size();                           //获得歌曲数目
                        
   	qDebug("ncount = %d",nCount);
   	if(nCount!=0)
   	fileName =  static_cast<QString>(musicList.at(0));   //提取歌曲名称
   
	QString tmp="\n";
	QString tmp3=".mp3";
	QString tmp4=".Mp3";
	QString tmp5=".MP3";
   
   	for(int i=0; i<nCount; i++) {

       QString tmp2;
       tmp2=static_cast<QString>(musicList.at(i))+tmp;
      
       if(tmp2.contains(tmp3) || tmp2.contains(tmp4) ||tmp2.contains(tmp5)){
       		listWidget->insertItem(i,new QListWidgetItem(QIcon(":/images/mp3.png"),tmp2,listWidget));
       		musiccount++;
        }
   }

   if(musiccount==0){
       system("killall -9 madplay");
       QDialog * setdialog = new QDialog;
       QLabel * settmp = new QLabel;
       settmp->setText(tr("该目录没有可打开的音乐!"));
       settmp->setStyleSheet("color:red;");
       QTimer*timer = new QTimer(setdialog);
       timer->start(1000);
       connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
       QGridLayout *tmplayout = new QGridLayout;
       tmplayout->addWidget(settmp,0,0,1,1);
       setdialog->setLayout(tmplayout);
       setdialog->setWindowFlags(Qt::FramelessWindowHint);
       setdialog->exec();
   }
}

void Music::scanMusicFun0()
{
    qDebug()<<"scanMusicFun0"; //这个函数是固定的播放目录,若没有歌曲就跳到这个目录
    QDir dir("/usrfs/qtapp/music/");
    filePath = "/usrfs/qtapp/music/";                    //设置播放目录
    listWidget->clear();
  //  Filters filter="*.mp3";
  //  dir.setFilter(filter);
    musicList = dir.entryList(QDir::Files,QDir::Name);   //遍历播放目录下的所有歌曲
  //  QList<QString> wifiList
    musiccount=0;
   nCount = musicList.size();                           //获得歌曲数目
 //  qDebug("nCount = %d",nCount);
   if(nCount!=0)
   fileName =  static_cast<QString>(musicList.at(0));   //提取歌曲名称
   QString tmp="\n";

   QString tmp3=".mp3";
   QString tmp4=".Mp3";
   QString tmp5=".MP3";
   for(int i=0;i<nCount;i++) {
       QString tmp2;
       tmp2=static_cast<QString>(musicList.at(i))+tmp;
       //)<<tmp2;
     //  listWidget->insertItem(i,new QListWidgetItem(tmp2,listWidget));
        if(tmp2.contains(tmp3) || tmp2.contains(tmp4) ||tmp2.contains(tmp5)){
       listWidget->insertItem(i,new QListWidgetItem(QIcon(":/images/mp3.png"),tmp2,listWidget));
       musiccount++;
        }
   }
   if(musiccount==0){
       system("killall -9 madplay");
       QDialog * setdialog = new QDialog;
       QLabel * settmp = new QLabel;
       settmp->setText(tr("该目录没有MP3文件"));
       settmp->setStyleSheet("color:red;");
       QTimer*timer = new QTimer(setdialog);
       timer->start(1000);
       connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));
       QGridLayout *tmplayout = new QGridLayout;
       tmplayout->addWidget(settmp,0,0,1,1);
       setdialog->setLayout(tmplayout);
       setdialog->setWindowFlags(Qt::FramelessWindowHint);
       setdialog->exec();
   }
}

void Music :: chosemusic()
{
    choncehanv=1;

	system("killall -9 madplay");         //停止播放当前歌曲
    QListWidgetItem*tmp=listWidget->currentItem();

	QString nowitem = tmp->text();
    QString nowitemtmp;
    qDebug("LinDbg: [%s]%d\n", __FUNCTION__, __LINE__);
	for(int i =0;i<nowitem.size();i++)
    {
        if(nowitem.at(i)!='\n')
             nowitemtmp.append(nowitem.at(i));
    }
	
    giftimer->start(1000);
	
    fileName =  nowitemtmp;   //提取歌曲名称
    
    currentsound = listWidget->currentRow();
	
    timerx->start(200);
	
    slotOpen();
}

void Music::startorstop()
{
	qDebug() << "startorstop()";

  if(choncehanv){
  	qDebug("choncehanv\n");
  	if(nCount){
  		qDebug("nCount\n");
    	startflag++;
       	timerx->start(200);

		if(startflag == 1)
	    {
	        system("killall -STOP madplay &");
	        starMusic->setText(tr("播放"));
	        timerx->stop();
	        timer->stop();
	    }
		
	    if(startflag == 2)
	    {
	        if(stopflag)
	        {
	            stopflag = 0;
	            slotOpen();
	        }
	        system("killall -CONT madplay &");
			
	        timerx->start();
	        timer->start();
	        starMusic->setText(tr("暂停"));
	        startflag=0;
    	}
  	}
  }
}

void Music::slotOpen()
{
	qDebug() << "slotOpen()!";
	

   	if(nCount){
		QString command_full = command;
		char *S;
		QFile vol_file("/tmp/volume");

		vol_file.open(QFile::ReadOnly);
		QString vol = vol_file.readAll();
		vol.replace(QString("\n"), QString(""));


		command_full.append(vol);
		command_full.append(" ");
		command_full.append(filePath);
        command_full.append(fileName);
		command_full.append(backend);
		
		qDebug()<<"command_full:"<<command_full;
        QFile musicFile(filePath+fileName);
        if(! musicFile.exists()){
            qDebug("LinDbg: muisc not exit, [%s]%d, fileName:%s \n", __FUNCTION__, __LINE__, qPrintable(fileName));
            QMessageBox::critical(this,"Error",tr("文件不存在，请重扫描目录"));
            return ;
        }
		timerx->start(200);

		S = (command_full.toAscii()).data();
		system(S);
        qDebug("LinDbg,[%s]%d, system(%s)", __FUNCTION__, __LINE__, S);
//		keepVolUmeFixed();

		information();
        qDebug("LinDbg,[%s]%d", __FUNCTION__, __LINE__);
		someset();
        qDebug("LinDbg,[%s]%d", __FUNCTION__, __LINE__);
		runSlider->setValue(0);
		addtime = inittime.addSecs(0);
        qDebug("LinDbg,[%s]%d", __FUNCTION__, __LINE__);
		starttime->setTime(addtime);
		starMusic->setText(tr("暂停"));
        qDebug("LinDbg,[%s]%d", __FUNCTION__, __LINE__);
   }
}

void Music::slotGetVol()
{
        int ret=0;
        usr_volume = slider->value();                //设置音量大小
      //  if(usr_volume>20)
      //  usr_volume -= 10;
         //"fd = %d",fd);
         //"usr_volume = %d",usr_volume);
         ioctl(fd,MIXER_WRITE(0),&usr_volume);        //调节音量

     //    ioctl(fd,MIXER_WRITE(SOUND_MIXER_VOLUME),slider->value());
     //   usr_volume=50*120;
       //  ret=ioctl(fd,SOUND_MIXER_WRITE_VOLUME,&usr_volume);
        // ret=ioctl(fd,SOUND_MIXER_VOLUME,&usr_volume);

         //"ret = %d",ret);
}




int flag =0;
void Music::slotStart()
{
       char *S;
        tm =0;
        ts =0;

		qDebug() << "slotStart()!";
//		slider->setValue((int)volume + 8);
		

        if(flag!=1)
           {system("killall -9 madplay");flag = 1;}
        else
        {
          flag=0;
            QString command_full = command;
            QFile vol_file("/tmp/volume");

		vol_file.open(QFile::ReadOnly);
		QString vol = vol_file.readAll();
		vol.replace(QString("\n"), QString(""));


		command_full.append(vol);
		command_full.append(" ");
		command_full.append(filePath);
		command_full.append(fileName);
		command_full.append(backend);
/*
            command_full.append(filePath);
            command_full.append(fileName);
            command_full.append(backend);
*/
            S = (command_full.toAscii()).data();
            printf("%s\n\r",S);
          //  timer->start(1000);        //设置定是器的时间为一秒
            system(S);
//		  	keepVolUmeFixed();

            information();
            someset();
            runSlider->setValue(0);
            addtime = inittime.addSecs(0);
            starttime->setTime(addtime);
        }
}

void Music::slotUp()
{
    usleep(300);
	qDebug()<<"slotup!";

    if(choncehanv)
    	if(musiccount)
    		if(nCount) {
		        QString command_full = command;
		        system("killall -9 madplay");         //停止播放当前歌曲

		       // index = musicList.indexOf(fileName);  //获取当前歌曲索引
		        index =listWidget->currentRow();
		        index--;                              //获取上一曲索引
		//        if(index < 0)
		//            index = nCount-1;
		        if(index < 0)
		            index = musiccount-1;


		        /* 根据上一曲索引找到上一曲文件名 */

		     //   fileName = static_cast<QString>(musicList.at(index))

		        listWidget->setCurrentRow(index);
		        QListWidgetItem*tmp=listWidget->currentItem();
		        QString nowitem = tmp->text();
		        //)<<nowitem;
		        QString nowitemtmp;
		        for(int i =0;i<nowitem.size();i++)
		        {
		            if(nowitem.at(i)!='\n')
		    //        nowitemtmp::append()=nowitem.at(i) ;
		                 nowitemtmp.append(nowitem.at(i));
		        }
		        fileName =  nowitemtmp;   //提取歌曲名称
		        flag = 1;
		        if(nCount)
		     //   if(musiccount)
		        slotStart();        //播放
    		}

    if(choncehanv)
    	if(nCount){
	      startflag=2;
	      timerx->start(200);

		  if(startflag==1)
	      {
	          system("killall -STOP madplay &");
	          starMusic->setText(tr("播放"));
	          timerx->stop();
	          timer->stop();
	      }

		  if(startflag==2)
	      {
	          if(stopflag)
	          {
	              stopflag=0;
	              slotOpen();
	          }
	          system("killall -CONT madplay &");
	          timerx->start();
	          timer->start();
	          starMusic->setText(tr("暂停"));
	          startflag=0;
      }
    }


}

void Music::slotDown()
{
    usleep(300);
	qDebug()<<"slotDown";
	
    if(choncehanv)
    if(musiccount)
    if(nCount) {
        QString command_full = command;
        system("killall -9 madplay");
      //  index = musicList.indexOf(fileName);
         index =listWidget->currentRow();

        index++;
//        if(index >(nCount-1))
//            index = 0;

        if(index >(musiccount-1))
            index = 0;
      //  fileName = static_cast<QString>(musicList.at(index));

        listWidget->setCurrentRow(index);
        QListWidgetItem*tmp=listWidget->currentItem();
        QString nowitem = tmp->text();
        //)<<nowitem;
        QString nowitemtmp;
        for(int i =0;i<nowitem.size();i++)
        {
            if(nowitem.at(i)!='\n')
    //        nowitemtmp::append()=nowitem.at(i) ;
                 nowitemtmp.append(nowitem.at(i));
        }
        fileName =  nowitemtmp;   //提取歌曲名称
        flag = 1;
        slotStart();
    }
    if(choncehanv)
    if(nCount){
      startflag=2;
         timerx->start(200);
      if(startflag==1)
      {
          system("killall -STOP madplay &");
          starMusic->setText(tr("播放"));
          timerx->stop();
          timer->stop();
      }
      if(startflag==2)
      {
          if(stopflag)
          {
              stopflag=0;
              slotOpen();
          }

		  system("killall -CONT madplay &");
          timerx->start();
          timer->start();
          starMusic->setText(tr("暂停"));
          startflag=0;
      }
    }
}

void Music::slotShowTime()
{
        char disp_buf[5];
        FILE *out;
        char str[30];

        ts++;
        if(ts >= 60) {
            tm++;
            ts = 0;
        }
        if(tm >= 60) {
            tm = 0;
            ts = 0;
        }

/*
        system("ps | pgrep -l madplay > /tmp/run.dat");


        QFile filetmpwifi("/tmp/run.dat");
        filetmpwifi.open(QFile::ReadOnly);
        QString stmp =filetmpwifi.readAll();
        QString stmp2="madplay";

		qDebug()<<"/tmp/run.dat:"<<stmp;
		
        if(!stmp.contains(stmp2) )
            if(nCount!=0){
				qDebug("nCount != 0!");
            	slotDown();
            	}
 */
}

void Music::musicsettingonce()
{

    index=0;
//    QString fileName = QFileDialog::getOpenFileName(this,
//                                    tr("选择MP3路径"), QDir::currentPath(),
//                                    "Music File(*.mp3)");
    QString fileName;

    Folder2 * folderTools = new Folder2(this,1);

    folderTools->setGeometry(100, 100, int_WIDGET_W-150, int_WIDGET_H-150);
    folderTools->exec();

    QFile file1("/usrfs/qtapp/music.conf");
    file1.open(QFile::ReadOnly);
    fileName=file1.readAll();
    file1.close();


    QByteArray temp = fileName.toUtf8();
    //temp.data());

    QFileInfo file(fileName);
    QString path = file.dir().absolutePath();

    temp = path.toUtf8();
    temp.append('/');
   // musicdir=temp.data();
    setpath=temp.data();

//    QFile file1("/etc/music.conf");
//    file1.open(QFile::WriteOnly);
//    QTextStream s(&file1);
//    s<<setpath;
//    file1.close();

	system("echo "" > /usrfs/qtapp/musichave.conf ");

    QFile file2("/usrfs/qtapp/musichave.conf");
    file2.open(QFile::WriteOnly);
    QTextStream s2(&file2);
    s2<<"haved";
    file2.close();
    system("sync");
}

void Music::musicsetting()
{

    index=0;

     QString fileName;

     Folder2 * folderTools = new Folder2(this,1);

     folderTools->setGeometry(100, 100, int_WIDGET_W-150, int_WIDGET_H-150);
     folderTools->exec();

//   fileName = QFileDialog::getOpenFileName(this,
 //                                   tr("选择MP3路径"), QDir::currentPath(),
 //                                   "Music File(*.mp3)");
//    QByteArray temp = fileName.toUtf8();
//    //temp.data());

//    QFileInfo file(fileName);
//    QString path = file.dir().absolutePath();

//    temp = path.toUtf8();
//    temp.append('/');
//   // musicdir=temp.data();
//    setpath=temp.data();

//    QFile file1("/etc/music.conf");
//    file1.open(QFile::WriteOnly);
//    QTextStream s(&file1);
//    s<<setpath;
//    file1.close();

	qDebug() << "path: " << fileName;

    scanMusicFun();

    QFile file2("/usrfs/qtapp/musichave.conf");
    file2.open(QFile::WriteOnly);
    QTextStream s2(&file2);
    s2<<"haved";
    file2.close();
    system("sync");


}

Music::~Music()
{
   // movie->stop();
  //  delete movie;
      system("killall -9 madplay");
}
